import tkinter as tk
from tkinter import filedialog, ttk, messagebox
import os
import sys
import threading
import pandas as pd
from excel_comparator import split_and_compare_excel
from example_data import create_example_data

class ExcelComparatorApp:
    def __init__(self, root):
        self.root = root
        self.root.title("Excel数据比对工具")
        self.root.geometry("600x600")
        self.root.resizable(True, True)
        
        # 设置样式
        self.style = ttk.Style()
        self.style.configure("TButton", font=("微软雅黑", 10))
        self.style.configure("TLabel", font=("微软雅黑", 10))
        self.style.configure("TEntry", font=("微软雅黑", 10))
        
        # 创建主框架
        main_frame = ttk.Frame(root, padding="20 20 20 20")
        main_frame.pack(fill=tk.BOTH, expand=True)
        
        # 文件选择部分
        file_frame = ttk.LabelFrame(main_frame, text="Excel", padding="10 10 10 10")
        file_frame.pack(fill=tk.X, pady=10)
        
        ttk.Label(file_frame, text="文件路径:").grid(row=0, column=0, sticky=tk.W, pady=5)
        
        self.file_path_var = tk.StringVar()
        file_path_entry = ttk.Entry(file_frame, textvariable=self.file_path_var, width=40)
        file_path_entry.grid(row=0, column=1, padx=5, pady=5, sticky=tk.W+tk.E)
        
        browse_btn = ttk.Button(file_frame, text="浏览...", command=self.browse_file)
        browse_btn.grid(row=0, column=2, padx=5, pady=5)
        
        # 创建示例数据按钮
        example_frame = ttk.Frame(file_frame)
        example_frame.grid(row=0, column=3, padx=5, pady=5)
        
      
        
        # 字段选择部分
        fields_frame = ttk.LabelFrame(main_frame, text="字段设置", padding="10 10 10 10")
        fields_frame.pack(fill=tk.X, pady=10)
        
        ttk.Label(fields_frame, text="拆分字段:").grid(row=0, column=0, sticky=tk.W, pady=5)
        self.split_field_var = tk.StringVar()
        self.split_field_combo = ttk.Combobox(fields_frame, textvariable=self.split_field_var, state="readonly")
        self.split_field_combo.grid(row=0, column=1, padx=5, pady=5, sticky=tk.W+tk.E)
        
        ttk.Label(fields_frame, text="比对字段:").grid(row=1, column=0, sticky=tk.W, pady=5)
        self.compare_field_var = tk.StringVar()
        self.compare_field_combo = ttk.Combobox(fields_frame, textvariable=self.compare_field_var, state="readonly")
        self.compare_field_combo.grid(row=1, column=1, padx=5, pady=5, sticky=tk.W+tk.E)
        
        load_fields_btn = ttk.Button(fields_frame, text="加载字段", command=self.load_fields)
        load_fields_btn.grid(row=0, column=2, rowspan=2, padx=5, pady=5)
        
        # 操作按钮
        buttons_frame = ttk.Frame(main_frame)
        buttons_frame.pack(fill=tk.X, pady=20)
        
        self.compare_btn = ttk.Button(buttons_frame, text="开始比对", command=self.start_comparison)
        self.compare_btn.pack(side=tk.RIGHT, padx=5)
        
        # 状态栏
        status_frame = ttk.Frame(main_frame, relief=tk.SUNKEN, borderwidth=1)
        status_frame.pack(fill=tk.X, side=tk.BOTTOM, pady=5)
        
        self.status_var = tk.StringVar()
        self.status_var.set("就绪")
        status_label = ttk.Label(status_frame, textvariable=self.status_var, anchor=tk.W)
        status_label.pack(fill=tk.X, padx=5)
        
        # 进度条
        self.progress = ttk.Progressbar(main_frame, orient=tk.HORIZONTAL, length=100, mode='indeterminate')
        self.progress.pack(fill=tk.X, pady=5)
        
        # 日志区域
        log_frame = ttk.LabelFrame(main_frame, text="操作日志", padding="10 10 10 10")
        log_frame.pack(fill=tk.BOTH, expand=True, pady=10)
        
        self.log_text = tk.Text(log_frame, wrap=tk.WORD, height=10, font=("微软雅黑", 9))
        self.log_text.pack(fill=tk.BOTH, expand=True, side=tk.LEFT)
        
        scrollbar = ttk.Scrollbar(log_frame, orient=tk.VERTICAL, command=self.log_text.yview)
        scrollbar.pack(fill=tk.Y, side=tk.RIGHT)
        self.log_text.configure(yscrollcommand=scrollbar.set)
        
        # 初始化
        self.df = None
    
    def log(self, message):
        self.log_text.insert(tk.END, message + "\n")
        self.log_text.see(tk.END)
        self.root.update_idletasks()
    
    def browse_file(self):
        file_path = filedialog.askopenfilename(
            title="选择Excel文件",
            filetypes=[("所有支持的文件", "*.xlsx *.xls"),("Excel文件", "*.xlsx *.xls")]
        )
        if file_path:
            self.file_path_var.set(file_path)
            self.log(f"已选择文件: {file_path}")
    
    
    
    def load_fields(self):
        file_path = self.file_path_var.get()
        if not file_path or not os.path.exists(file_path):
            messagebox.showerror("错误", "请先选择有效的Excel文件")
            return
        
        try:
            self.status_var.set("正在加载字段...")
            self.progress.start()
            
            # 在新线程中加载字段
            def load_fields_thread():
                try:
                    file_ext = os.path.splitext(file_path)[1].lower()
                    
                    self.df = pd.read_excel(file_path, nrows=1)
                    columns = list(self.df.columns)
                    
                    self.root.after(0, lambda: self.split_field_combo.configure(values=columns))
                    self.root.after(0, lambda: self.compare_field_combo.configure(values=columns))
                    
                    if columns:
                        self.root.after(0, lambda: self.split_field_var.set(columns[0]))
                        self.root.after(0, lambda: self.compare_field_var.set(columns[0]))
                    
                    self.root.after(0, lambda: self.log(f"已加载字段: {', '.join(columns)}"))
                    self.root.after(0, lambda: self.status_var.set("字段加载完成"))
                    self.root.after(0, lambda: self.progress.stop())
                except Exception as e:
                    self.root.after(0, lambda: self.log(f"加载字段时出错: {str(e)}"))
                    self.root.after(0, lambda: self.status_var.set("就绪"))
                    self.root.after(0, lambda: self.progress.stop())
            
            threading.Thread(target=load_fields_thread).start()
        except Exception as e:
            self.log(f"加载字段时出错: {str(e)}")
            self.status_var.set("就绪")
            self.progress.stop()
    
    def start_comparison(self):
        def log_to_gui(message):
            self.log(message)
        
        file_path = self.file_path_var.get()
        split_field = self.split_field_var.get()
        compare_field = self.compare_field_var.get()
        
        if not file_path or not os.path.exists(file_path):
            messagebox.showerror("错误", "请先选择有效的Excel文件")
            return
        
        if not split_field:
            messagebox.showerror("错误", "请选择拆分字段")
            return
        
        if not compare_field:
            messagebox.showerror("错误", "请选择比对字段")
            return
        
        try:
            self.status_var.set("正在进行比对...")
            self.progress.start()
            self.compare_btn.configure(state="disabled")
            
            # 在新线程中执行比对
            def compare_thread():
                try:
                    result = split_and_compare_excel(file_path, split_field, compare_field, log_to_gui)
                    
                    if result:
                        file_name, file_ext = os.path.splitext(file_path)
                        output_file = f"{file_name}_比对结果{file_ext}"
                        
                        self.root.after(0, lambda: self.log(f"比对完成，结果已保存到: {output_file}"))
                        self.root.after(0, lambda: messagebox.showinfo("完成", f"比对完成，结果已保存到:\n{output_file}"))
                    else:
                        self.root.after(0, lambda: self.log("比对失败，请检查日志信息"))
                    
                    self.root.after(0, lambda: self.status_var.set("比对完成"))
                    self.root.after(0, lambda: self.progress.stop())
                    self.root.after(0, lambda: self.compare_btn.configure(state="normal"))
                except Exception as e:
                    self.root.after(0, lambda: self.log(f"比对过程中出错: {str(e)}"))
                    self.root.after(0, lambda: self.status_var.set("就绪"))
                    self.root.after(0, lambda: self.progress.stop())
                    self.root.after(0, lambda: self.compare_btn.configure(state="normal"))
            
            threading.Thread(target=compare_thread).start()
        except Exception as e:
            self.log(f"启动比对过程时出错: {str(e)}")
            self.status_var.set("就绪")
            self.progress.stop()
            self.compare_btn.configure(state="normal")

def main():
    root = tk.Tk()
    app = ExcelComparatorApp(root)
    root.mainloop()

if __name__ == "__main__":
    main()